package rabbit.flt.plugins.springmvc;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import java.io.IOException;

/**
 * ServletOutputStream wrapper
 */
public class OutputStreamWrapper extends ServletOutputStream {

    private ServletOutputStream outputStream;

    private ServletResponseWrapper wrapper;

    public OutputStreamWrapper(ServletOutputStream outputStream, ServletResponseWrapper wrapper) {
        this.outputStream = outputStream;
        this.wrapper = wrapper;
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        outputStream.write(b, off, len);
        // 可能多次callback, 后续的将会被忽略
        this.wrapper.getCallBack().accept(new String(b, off, len));
    }

    @Override
    public boolean isReady() {
        return outputStream.isReady();
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {
        // ignore
    }

    @Override
    public void write(int b) throws IOException {
        outputStream.write(b);
    }

    @Override
    public void flush() throws IOException {
        outputStream.flush();
    }

    @Override
    public void close() throws IOException {
        outputStream.close();
    }
}
